from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base

# 配置数据库连接信息
# 格式: postgresql+psycopg2://username:password@host:port/database_name
DATABASE_URL = "postgresql+psycopg2://junluo:qaz159357@127.0.0.1:5432/my_alg"

# 创建数据库引擎
engine = create_engine(DATABASE_URL)

# 创建会话工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 创建基类模型
Base = declarative_base()

# 依赖函数，用于获取数据库会话
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()



def test_db_connection():
    from sqlalchemy import text
    try:
        with engine.connect() as connection:
            # 查询当前数据库中所有用户表
            result = connection.execute(text("""
                SELECT table_name
                FROM information_schema.tables
                WHERE table_schema = 'public'
                AND table_type = 'BASE TABLE'
            """))
            tables = [row[0] for row in result.fetchall()]
            print("数据库中的所有表:")
            for table in tables:
                print(table)
            return tables
    except Exception as e:
        print(f"查询表信息失败: {e}")
        return []

if __name__ == "__main__":
    test_db_connection()